//
//  ShopGoodInfoViewController.m
//  BaseFrame
//
//  Created by 孟学浩 on 2017/5/18.
//  Copyright © 2017年 com.mxh. All rights reserved.
//

#import "ShopGoodInfoViewController.h"
#import "ShopGoodInfoOneTableViewCell.h"
#import "ShopGoodInfoTableViewCell.h"

@interface ShopGoodInfoViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    BOOL state;
}
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIImageView *headerImgView;
@property (nonatomic,strong) UIView *footerView;

@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) NSMutableArray *imgArray;
@property (nonatomic,strong) NSDictionary *dataDictionary;


@end

//网络
@implementation ShopGoodInfoViewController (NetWorking)

- (void)getAddShopGood{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"sId":[UserModel sharedInstanced].s_id,
                                 @"ccId":self.ccId,
                                 @"agName":self.dataArray[0][@"key"],
                                 @"unitPrice":self.dataArray[1][@"key"],
                                 @"agStandard":self.dataArray[2][@"key"],
                                 @"agSize":self.dataArray[3][@"key"],
                                 @"agUnit":self.dataArray[4][@"key"],
                                 @"agIntroduce":self.dataArray[5][@"key"],};
 
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Auditing_Goods/newAuditItems.action" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *data = UIImageJPEGRepresentation(self.headerImgView.image, .1);
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
        [formData appendPartWithFileData:data name:@"file1" fileName:[NSString stringWithFormat:@"%ld.jpg",(unsigned long)time] mimeType:@"image/jpeg"];
        for (int i = 0; i < self.imgArray.count; i ++) {
            if ([self.imgArray[i] isKindOfClass:[UIImage class]]) {
                NSData *data = UIImageJPEGRepresentation(self.imgArray[i], .1);
                NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
                [formData appendPartWithFileData:data name:@"files" fileName:[NSString stringWithFormat:@"%ld.jpg",(NSUInteger)time] mimeType:@"image/jpeg"];
            }
        }
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            [self.view makeToast:responseObject[@"msg"] duration:1 position:CSToastPositionCenter title:nil image:nil style:nil completion:^(BOOL didTap) {
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        [self hiddenProgressHUD];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];
}

- (void)getData{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"c_id":self.c_id};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Commodity/viewCommodityInformation.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            NSDictionary *dic = responseObject[@"obj"];
            self.dataArray[0][@"key"] = dic[@"c_name"];
            self.dataArray[1][@"key"] = dic[@"unit_price"];
            self.dataArray[2][@"key"] = dic[@"c_standard"];
            self.dataArray[3][@"key"] = dic[@"c_size"];
            self.dataArray[4][@"key"] = dic[@"c_unit"];
            self.dataArray[5][@"key"] = dic[@"c_introduce"];
            [self.headerImgView sd_setImageWithURL:[NSURL URLOffsetIPWithString:dic[@"first_picture"]]];
            self.headerImgView.contentMode = UIViewContentModeScaleAspectFill;
            
            if (![dic[@"picture_one"] isEqualToString:@" "]) {
                [self.imgArray removeAllObjects];
                [self.imgArray addObject:dic[@"picture_one"]];
            }
            if (![dic[@"picture_two"] isEqualToString:@" "]) {
                [self.imgArray addObject:dic[@"picture_two"]];
            }
            if (![dic[@"picture_three"] isEqualToString:@" "]) {
                [self.imgArray addObject:dic[@"picture_three"]];
            }
            if (self.imgArray.count != 3 && ![self.imgArray[0] isEqualToString:@""]) {
                [self.imgArray addObject:@""];
            }
            
            [self.tableView reloadData];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

- (void)getUpdateComm{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"c_id":self.c_id,
                                 @"c_name":self.dataArray[0][@"key"],
                                 @"unit_price":self.dataArray[1][@"key"],
                                 @"c_standard":self.dataArray[3][@"key"],
                                 @"c_size":self.dataArray[4][@"key"],
                                 @"c_unit":self.dataArray[5][@"key"],
                                 @"c_introduce":self.dataArray[2][@"key"],};
     
     [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Commodity/updateComm.action" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *data = UIImageJPEGRepresentation(self.headerImgView.image, .1);
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
        [formData appendPartWithFileData:data name:@"file1" fileName:[NSString stringWithFormat:@"%ld.jpg",(NSUInteger)time] mimeType:@"image/jpeg"];
        for (int i = 0; i < self.imgArray.count; i ++) {
            if ([self.imgArray[i] isKindOfClass:[UIImage class]]) {
                NSData *data = UIImageJPEGRepresentation(self.imgArray[i], .1);
                NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
                [formData appendPartWithFileData:data name:@"files" fileName:[NSString stringWithFormat:@"%ld.jpg",(NSUInteger)time] mimeType:@"image/jpeg"];
            }
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"ResponseStatus"] isEqualToString:@"0"]) {
            [self.view makeToast:responseObject[@"msg"] duration:1 position:CSToastPositionCenter title:nil image:nil style:nil completion:^(BOOL didTap) {
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        [self hiddenProgressHUD];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];
}

@end

//UI
@implementation ShopGoodInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    switch (self.type) {
        case ShopGoodsType_Add:
            self.navigationItem.title = @"添加商品";
            state = NO;
            break;
        case ShopGoodsType_Change:
            self.navigationItem.title = @"商品详情";
            state = YES;
            break;
        default:
            break;
    }
    
    UIButton * rightButton = [[UIButton alloc]init];
    rightButton.size = CGSizeMake(40, 20);
    [rightButton setTitle:@"保存" forState:UIControlStateNormal];
    [rightButton.titleLabel setFont:DEF_FontSize_12];
    rightButton.layer.masksToBounds = YES;
    rightButton.layer.cornerRadius = 3;
    rightButton.layer.borderColor = [[UIColor whiteColor] CGColor];
    rightButton.layer.borderWidth = 1;
    [rightButton addTarget:self action:@selector(rightBarButtonItemClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    //设置barbutton
    self.navigationItem.rightBarButtonItem = rightItem;
    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick)];
    [self.view addSubview:self.tableView];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

#pragma mark - cilck

- (void)rightBarButtonItemClick{
    if (!state) {
        ShowMessage(@"请选择店铺展示图片");
        return;
    }
    for (int i = 0; i < self.dataArray.count; i ++) {
        if ([self.dataArray[i][@"key"] isEqualToString:@""]) {
            ShowMessage(self.dataArray[i][@"ph"]);
            return;
        }
    }
    switch (self.type) {
        case ShopGoodsType_Add:
            [self getAddShopGood];
            break;
        case ShopGoodsType_Change:
            [self getUpdateComm];
            break;
        default:
            break;
    }
}

- (void)tableHeadViewCkick{
    [self selectPhotoAlbumWithSelectPhotoHandle:^(UIImage *img) {
        self.headerImgView.image = img;
        self.headerImgView.contentMode = UIViewContentModeScaleAspectFill;
        state = YES;
    }];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return section == 0 ? self.dataArray.count : self.imgArray.count ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        ShopGoodInfoOneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ShopGoodInfoOneTableViewCell class])];
        cell.dataDictionary = self.dataArray[indexPath.row];
        cell.getTextFieldClick = ^(NSString *str) {
            self.dataArray[indexPath.row][@"key"] = str;
        };
        
        return cell;
    }else{
        if ([self.imgArray[indexPath.row] isKindOfClass:[NSString class]] && [self.imgArray[indexPath.row] isEqualToString:@""]) {
            ShopGoodInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ShopGoodInfoTableViewCell class])];
            cell.imgView.image = [UIImage imageNamed:@"button_mapadd"];
            cell.imgView.contentMode = UIViewContentModeCenter;
            cell.deleteButton.hidden = YES;
            return cell;
        }else{
            ShopGoodInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ShopGoodInfoTableViewCell class])];
            if ([self.imgArray[indexPath.row] isKindOfClass:[NSString class]]) {
                cell.model = self.imgArray[indexPath.row];
            }else{
                cell.sdImage = self.imgArray[indexPath.row];
            }
            cell.deleteButton.hidden = NO;
            cell.imgView.contentMode = UIViewContentModeScaleAspectFill;
            cell.getDeleteClick = ^{
                
                [self.imgArray removeObjectAtIndex:indexPath.row];
                if (self.imgArray.count == 2) {
                    [self.imgArray addObject:@""];
                }
                [self.tableView reloadData];
                
            };
            return cell;
        }
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        [self selectPhotoAlbumWithSelectPhotoHandle:^(UIImage *img) {
            self.imgArray[indexPath.row] = img;
            if (indexPath.row == self.imgArray.count - 1 && self.imgArray.count != 3) {
                [self.imgArray addObject:@""];
            }
            [self.tableView reloadData];
        }];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return indexPath.section == 0 ? 44 : 120/WIDTH_5S_SCALE;
}

#pragma mark - set & get

- (void)setC_id:(NSString *)c_id{
    _c_id = c_id;
    [self getData];
}

- (UITableView *)tableView{
    if (!_tableView) {
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.sectionFooterHeight = .01;
        _tableView.sectionHeaderHeight = .01;
        _tableView.tableFooterView = self.footerView;
        _tableView.tableHeaderView = self.headerImgView;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.backgroundColor = [UIColor whiteColor];
        [_tableView registerClass:[ShopGoodInfoOneTableViewCell class] forCellReuseIdentifier:NSStringFromClass([ShopGoodInfoOneTableViewCell class])];
        [_tableView registerClass:[ShopGoodInfoTableViewCell class] forCellReuseIdentifier:NSStringFromClass([ShopGoodInfoTableViewCell class])];

    }
    return _tableView;
}

- (UIImageView *)headerImgView{
    if (!_headerImgView) {
        _headerImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 130/WIDTH_5S_SCALE)];
        _headerImgView.image = [UIImage imageNamed:@"button_mapadd"];
        _headerImgView.backgroundColor = getColor(@"f1f2f6");
        _headerImgView.contentMode = UIViewContentModeCenter;
        _headerImgView.layer.masksToBounds = YES;
        _headerImgView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tableHeadViewCkick)];
        [_headerImgView addGestureRecognizer:tap];
    }
    return _headerImgView;
}

- (UIView *)footerView{
    if (!_footerView) {
        _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        _footerView.backgroundColor = [UIColor whiteColor];
        UILabel *label = [[UILabel alloc] initWithFrame:_footerView.bounds];
        label.text = @"商品图片限制3张";
        label.font = DEF_FontSize_12;
        label.textAlignment = NSTextAlignmentCenter;
        [_footerView addSubview:label];
        [_footerView addSubview:label];
    }
    return _footerView;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = @[@{@"title":@"商品名称",
                         @"ph":@"请输入商品名称",
                         @"key":@""}.mutableCopy,
                       @{@"title":@"商品单价",
                         @"ph":@"请输入商品单价",
                         @"key":@""}.mutableCopy,
                       @{@"title":@"商品规格",
                         @"ph":@"请输入商品规格",
                         @"key":@""}.mutableCopy,
                       @{@"title":@"商品尺寸",
                         @"ph":@"请输入商品尺寸",
                         @"key":@""}.mutableCopy,
                       @{@"title":@"商品单位",
                         @"ph":@"请输入商品单位",
                         @"key":@""}.mutableCopy,
                       @{@"title":@"商品介绍",
                         @"ph":@"请输入商品介绍",
                         @"key":@""}.mutableCopy].mutableCopy;
    }
    return _dataArray;
}

- (NSMutableArray *)imgArray{
    if (!_imgArray) {
        _imgArray = @[].mutableCopy;
        [_imgArray addObject:@""];
    }
    return _imgArray;
}

- (NSDictionary *)dataDictionary{
    if (!_dataDictionary) {
        _dataDictionary = @{};
    }
    return _dataDictionary;
}

@end
